package com.pro.ydl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.net.RequestListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.EditText;
import android.widget.Toast;

public class YDLWeiBoShare  extends Activity implements WeiboAuthListener, RequestListener{
	
	/*activity object context*/
	public Context contextWeiBo;
	private static final String Tag = "YDLWeiBoShare";
	private static final String CONSUMER_KEY = "1632962186";
	private static final String CONSUMER_SECRET = "bfbea127116a92c31dea8cf80a8b7517";
	//http://www.sina.com.cn//815986801//9c9e08f115915b03362aba947c65b39c
	private static final String REDIRECT_URL = "http://www.yundongling.com/weiboredirect.aspx";
	private String sPicturePath;
	private String strShareMessage;
	public Weibo weibo;
	public View viewShare;
	public Oauth2AccessToken AccessToken;
	public AlertDialog ADWeiBoInsertTextDialog;
	public EditText ETInsertInfo;
	public String sWeiBoMessage;
	private final Handler handle = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			switch(msg.what)
			{
				case WEIBO_SHARE_RESULT:
				{
					if(msg.arg1 == -1)
					{
						ShowToast(contextWeiBo, "分享异常，请重试！");
					}
					else if (msg.arg1 == 0)
					{
						String sTempMessage=null;
						if(true == sWeiBoMessage.contains("20008"))
						{
							sTempMessage ="分享错误：输入内容为空！";
						}
						else if(true == sWeiBoMessage.contains("20012"))
						{
							sTempMessage ="分享错误：输入内容过长！";
						}
						else if(true == sWeiBoMessage.contains("20019"))
						{
							sTempMessage ="分享错误：分享了相同的微博！";
						}
						else
						{
							sTempMessage="分享错误：请重试";
						}
						ShowToast(contextWeiBo, sTempMessage);
					}
					else
					{
						ShowToast(contextWeiBo, "分享成功");
					}
					ADWeiBoInsertTextDialog.dismiss();
				}
				break;
			}
		}
	};
	private static final int WEIBO_SHARE_RESULT = 1;
	YDLWeiBoShare(Context con,View view, String shareMessage)
	{
		contextWeiBo = con;
		viewShare = view;
		strShareMessage = shareMessage;
		String sAPPPath = contextWeiBo.getFilesDir().getAbsolutePath();
		sPicturePath = sAPPPath+"YDLShareTable.jpg";
	}
	
	public void onShare()
	{
		weibo = Weibo.getInstance(CONSUMER_KEY, REDIRECT_URL);
		weibo.authorize(contextWeiBo, this);
	}
	
	@Override
	public void onCancel() {
		// TODO Auto-generated method stub
		Toast.makeText(contextWeiBo, "授权取消", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onComplete(Bundle arg0) {
		// TODO Auto-generated method stub
		try
		{
		Toast.makeText(contextWeiBo, "授权成功", Toast.LENGTH_SHORT).show();

		String Token = arg0.getString("access_token");
		String expires_in = arg0.getString("expires_in");
		this.AccessToken = new Oauth2AccessToken(Token,expires_in);
		//LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
		LayoutInflater inflater = LayoutInflater.from(contextWeiBo); 
		final View layout = inflater.inflate(R.layout.dialog_style, null);
		ADWeiBoInsertTextDialog = null;
		AlertDialog dialog = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(contextWeiBo);
		if(AccessToken.isSessionValid())
		{
			//ADWeiBoInsertTextDialog
			ETInsertInfo = (EditText)layout.findViewById(R.id.shareContent);  
			//ETInsertInfo.setText("我使用运动令分享了我的运动信息，你也赶快来..");   
			//ADWeiBoInsertTextDialog = new AlertDialog.Builder(contextWeiBo)
					//.setTitle("分享")   
	                //.setIcon(R.drawable.action_search)
	                //.setView(ETInsertInfo)   
			builder.setInverseBackgroundForced(true).setView(layout).setPositiveButton("分享", new DialogInterface.OnClickListener() {   
	                    @Override   
	                    public void onClick(DialogInterface arg0, int arg1) {   
	                    	final EditText edit = (EditText)layout.findViewById(R.id.shareContent);
	                    	String text=edit.getText().toString();
	                    	WeiBoInfoCommit(text);
	                    }   
	                }).setNegativeButton("取消账号绑定", new DialogInterface.OnClickListener(){

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							WeiboClearCookies();
						}
	                	
	                });
			ADWeiBoInsertTextDialog = builder.show();
			ADWeiBoInsertTextDialog.setView(layout, 0, 0, 0, 0);
			ETInsertInfo.setText(strShareMessage);
		}
		else
		{
			Toast.makeText(contextWeiBo, "不可得到access", Toast.LENGTH_SHORT).show();
		}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
	}
	public void WeiboClearCookies()
	{
		CookieSyncManager.createInstance(contextWeiBo);  
		CookieSyncManager.getInstance().startSync();  
		CookieManager.getInstance().removeAllCookie();
		Toast.makeText(contextWeiBo, "取消绑定成功", Toast.LENGTH_SHORT).show();
	}
	public void WeiBoInfoCommit(String title)
	{
		

		// TODO Auto-generated method stub

		try
		{

		if(AccessToken.isSessionValid())
		{
			StatusesAPI API= new StatusesAPI(this.AccessToken);
			
			/*转化view为file*/
			convertviewtobitmapsave(viewShare);
			
			if(new File(sPicturePath).exists())
			{

				String sPicName = title;
				API.upload(sPicName, sPicturePath, null, null, this);
			}
			else
			{
				Toast.makeText(contextWeiBo, "无SD卡", Toast.LENGTH_SHORT).show();
			}
			
		}
		}
		catch(Exception e)
		{
			Toast.makeText(contextWeiBo, "分享异常", Toast.LENGTH_SHORT).show();
		}
		ADWeiBoInsertTextDialog.dismiss();
	
	}
	@Override
	public void onError(WeiboDialogError arg0) {
		// TODO Auto-generated method stub
		Toast.makeText(contextWeiBo, "授权error:"+arg0.getMessage(), Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onWeiboException(WeiboException arg0) {
		// TODO Auto-generated method stub
		Toast.makeText(contextWeiBo, "授权异常:"+arg0.getMessage(), Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onComplete(String arg0) {
		// TODO Auto-generated method stub
		//Toast.makeText(contextWeiBo, "分享成功", Toast.LENGTH_SHORT).show();
		Message msg = new Message();
		msg.what = WEIBO_SHARE_RESULT;
		msg.arg1 = 1;
		handle.sendMessage(msg);
	}

	@Override
	public void onError(WeiboException arg0) {
		// TODO Auto-generated method stub
		sWeiBoMessage = arg0.getMessage();
		//Toast.makeText(contextWeiBo, "分享错误"+arg0.getMessage(), Toast.LENGTH_SHORT).show();
		Message msg = new Message();
		msg.what = WEIBO_SHARE_RESULT;
		msg.arg1 = 0;
		handle.sendMessage(msg);
	}

	@Override
	public void onIOException(IOException arg0) {
		// TODO Auto-generated method stub
		//sWeiBoMessage = arg0.getMessage();
		//Toast.makeText(contextWeiBo, "分享异常"+arg0.getMessage(), Toast.LENGTH_SHORT).show();
		Message msg = new Message();
		msg.what = WEIBO_SHARE_RESULT;
		msg.arg1 = -1;
		handle.sendMessage(msg);
	}
	
	/*创建本地table图片*/
	public void convertviewtobitmapsave(View viewConverted)
	{
		Bitmap viewBitmap = Bitmap.createBitmap(viewConverted.getWidth(), viewConverted.getHeight(),Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(viewBitmap);
		viewConverted.draw(canvas);

        File f = new File(sPicturePath);
        if(f.exists())
        {
        	f.delete();
        }
        try {
			f.createNewFile();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        FileOutputStream fOut = null;
        try {
                fOut = new FileOutputStream(f);
        } catch (Exception e) {
                e.printStackTrace();
        }
        viewBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        try {
                fOut.flush();
        } catch (IOException e) {
                e.printStackTrace();
        }
        try {
                fOut.close();
        } catch (IOException e) {
                e.printStackTrace();
        }
	}
	public void ShowToast(Context context, String strShowMessage) {
		Toast toast = Toast.makeText(context, strShowMessage,
				Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
}
